package com.ruoyi.web.controller.basicInformation;

import java.util.Collections;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Validator;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.basicInformation.domain.TAppUser;
import com.ruoyi.system.basicInformation.domain.TTerminal;
import com.ruoyi.system.basicInformation.service.ITTerminalService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
//import io.micrometer.core.instrument.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.metadata.facets.Validatable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.basicInformation.vo.TAppUserVo;
import com.ruoyi.system.basicInformation.bo.TAppUserQueryBo;
import com.ruoyi.system.basicInformation.bo.TAppUserAddBo;
import com.ruoyi.system.basicInformation.bo.TAppUserEditBo;
import com.ruoyi.system.basicInformation.service.ITAppUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * APP用户Controller
 *
 * @author ruoyi
 * @date 2021-05-21
 */
@Api(value = "APP用户控制器", tags = {"APP用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/basicInformation/appUser")
public class TAppUserController extends BaseController {

    private final ITAppUserService iTAppUserService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ITTerminalService terminalService;

    /**
     * 查询APP用户列表
     */
    @ApiOperation("查询APP用户列表")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:list')")
    @GetMapping("/list")
    public TableDataInfo<SysUser> list(SysUser bo) {
        startPage();
        List<SysUser> list = userService.selectUserList(bo);
        return getDataTable(list);
    }

    /**
     * 查询APP用户列表
     */
    @ApiOperation("查询APP用户列表")
    @GetMapping("/touristList")
    public TableDataInfo<SysUser> touristList(SysUser bo) {
        startPage();
        List<SysUser> list = userService.touristList(bo);
        return getDataTable(list);
    }

    /**
     * 查询最后定位坐标的人员
     */
    @ApiOperation("查询最后定位坐标的人员")
//    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:list')")
    @GetMapping("/listUserCurrentPoint")
    public TableDataInfo<SysUser> listUserCurrentPoint(SysUser bo) {
        startPage();
        List<SysUser> list = userService.listUserCurrentPoint(bo);
        return getDataTable(list);
    }

    @Log(title = "APP用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, int userType) throws Exception {
        ExcelUtil<TAppUser> util = new ExcelUtil<TAppUser>(TAppUser.class);
        List<TAppUser> userList = util.importExcel(file.getInputStream());
//        userList.forEach(item ->{
//            if(Validator.isEmpty(item.getContact()) || Validator.isEmpty(item.getIdcard())){
//                throw new BaseException("用户导入失败,手机号码、身份证信息不能为空！");
//            }
//        });
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = iTAppUserService.importUser(userList, updateSupport, operName, userType);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<TAppUser> util = new ExcelUtil<TAppUser>(TAppUser.class);
        return util.importTemplateExcel("APP用户数据");
    }

    /**
     * 导出APP用户列表
     */
    @ApiOperation("导出APP用户列表")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:export')")
    @Log(title = "APP用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<SysUser> export(SysUser user) {
//        startPage();
        if (user.getIds() != null && user.getIds().length > 0) {
            user.setUserIdsStr(StringUtils.join(user.getIds(), ","));
        }
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     * 获取APP用户详细信息
     */
    @ApiOperation("获取APP用户详细信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:query')")
    @GetMapping("/{id}/{type}")
    public AjaxResult<SysUser> getInfo(@PathVariable("id") Long userId, @PathVariable("type") Long type) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("posts", postService.selectPostAll());
        if (type == 1) {
            ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> r.getRoleKey().startsWith("ym_")).collect(Collectors.toList()));
        } else {
            ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> r.getRoleKey().startsWith("xh_")).collect(Collectors.toList()));
        }
        if (Validator.isNotNull(userId) && userId != 0) {
            if (type != 3)
                ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            else
                ajax.put(AjaxResult.DATA_TAG, userService.selectTouristById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));

        } else if (userId == 0) {
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;

    }

    /**
     * PC端新增APP用户
     */
    @ApiOperation("新增APP用户")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:add')")
    @Log(title = "APP用户", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkIdCodeUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，身份证已存在");
        } else if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int result = userService.insertUser(user);
        //绑定终端
        terminalService.updateTerminalByObjId(user.getTerminalId(), user.getUserId());
        return toAjax(result);
//        return toAjax(iTAppUserService.insertByAddBo(bo) ? 1 : 0);
    }

    /**
     * 解绑终端设备
     */
    @ApiOperation("解绑终端设备")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:edit')")
    @Log(title = "解绑终端设备", businessType = BusinessType.UPDATE)
    @PostMapping("/unBundling")
    public AjaxResult<Void> unBundling(@RequestBody SysUser bo) {
        return toAjax(terminalService.unBundling(bo.getTerminalId()) ? 1 : 0);
    }


    /**
     * 新增APP用户
     */
    @ApiOperation("新增APP用户")
    @Log(title = "APP用户", businessType = BusinessType.INSERT)
    @PostMapping("/addAppUser")
    public AjaxResult addAppUser(@Validated @RequestBody SysUser user) {
        //设置为渔民
        user.setUserType("1");
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkTheUserNameUnique(user.getName(), (long) 0))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，名字已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkIdCodeUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，身份证已存在");
        } else if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改APP用户
     */
    @ApiOperation("修改APP用户")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:edit')")
    @Log(title = "APP用户", businessType = BusinessType.UPDATE)
    @PutMapping()
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkIdCodeUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，身份证已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkTheUserNameUnique(user.getName(), user.getUserId()))) {
            return AjaxResult.error("修改用户'" + user.getName() + "'失败，名字已存在");
        } else if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        //绑定终端
        if (user.getTerminalId() != user.getTerminalIdOld()) {
            terminalService.unBundling(user.getTerminalIdOld());
        }
        terminalService.updateTerminalByObjId(user.getTerminalId(), user.getUserId());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除APP用户
     */
    @ApiOperation("删除APP用户")
    @PreAuthorize("@ss.hasPermi('basicInformation:appUser:remove')")
    @Log(title = "APP用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (int i = 0; i < ids.length; i++) {

            SysUser tCarVo = userService.selectUserById(ids[i]);

            terminalService.unBundling(tCarVo.getTerminalId() != null ? tCarVo.getTerminalId().longValue() : 0);
        }
        return toAjax(userService.deleteUserByIds(ids));
    }
}
